package singsong;

import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.IOException;

import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.Clip;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JLabel;

public class TrackDataDebugger implements ActionListener {

	private JFrame frame;

	public TrackDataDebugger() {
	}

	public void createAndShowGUI() {
		frame = new JFrame("Track Data Debugger");
		frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		
		JButton analyzeButton = new JButton("Analyze");
		analyzeButton.addActionListener(this);
		analyzeButton.setActionCommand("analyze");		
		frame.getContentPane().add(analyzeButton, BorderLayout.WEST);
		
		JButton graphButton = new JButton("Graph");
		graphButton.addActionListener(this);
		graphButton.setActionCommand("graph");		
		frame.getContentPane().add(graphButton, BorderLayout.EAST);

		frame.setLocation(400, 300);
		frame.pack();

		frame.setVisible(true);
	}

	@Override
	public void actionPerformed(ActionEvent event) {
		if (event.getActionCommand().equals("analyze")) {
			runAnalysis();
		} else if (event.getActionCommand().equals("graph")) {
			graphTrackData();
		}
	}
	
	private void runAnalysis() {
		JFileChooser chooser = new JFileChooser();
		int returnVal = chooser.showOpenDialog(frame);
		if (returnVal == JFileChooser.APPROVE_OPTION) {
			TrackDataBuilder builder = new TrackDataBuilder(chooser.getSelectedFile().getAbsolutePath(), 100, 0);
			loadTrackDataFrame(builder.build());
		}
	}
	
	private void graphTrackData() {
		JFileChooser chooser = new JFileChooser();
		int returnVal = chooser.showOpenDialog(frame);
		if (returnVal == JFileChooser.APPROVE_OPTION) {
			try {
				SongFileReader reader = new SongFileReader();
				TrackData data = reader.readTrackDataFile(chooser.getSelectedFile());
				loadTrackDataFrame(data);
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}
	
	public void loadTrackDataFrame(TrackData data) {
		BarGraphFactory.BarGraphProperties props = new BarGraphFactory.BarGraphProperties();
		props.showVolume = true;
		props.width=1024;
		props.height=768;
		JLabel label = BarGraphFactory.create(data, props);
		
		JFrame frame = new JFrame("");
		frame.getContentPane().add(label);
		frame.setLocation(400, 300);
		frame.pack();

		frame.setVisible(true);
	}
	
	public static void main(String[] args) {
		final TrackDataDebugger app = new TrackDataDebugger();
		javax.swing.SwingUtilities.invokeLater(new Runnable() {
			public void run() {
				app.createAndShowGUI();
			}
		});
	}
}
